package cn.qiyu5522.timer;

import cn.qiyu5522.constant.SystemConsKeys;
import cn.qiyu5522.domain.entity.Article;
import cn.qiyu5522.service.ArticleService;
import cn.qiyu5522.utils.RedisCache;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: UpdateViewCountJob
 * Package: cn.qiyu5522.timer
 * Description:  每 10 分钟将 redis 中 阅读量 存入 mysql
 *
 * @Author: Tonkey
 * @Create：2024/4/15-16:04
 * @Version: v1.0
 */
@Component
public class UpdateViewCountJob {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ArticleService articleService;



    //定时任务每隔10分钟把Redis中的浏览量更新到数据库中
    @Scheduled(cron = "* 0/10 * * * ? ")
    public void updateViewCountToDB(){
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConsKeys.ARTICLE_VIEW_COUNT);
        List<Article> articles = viewCountMap.entrySet().stream().map(
                entry -> {
                    Article article = new Article();
                    article.setId(Long.valueOf(entry.getKey()));
                    article.setViewCount(entry.getValue().longValue());
                    return article;
                }
        ).collect(Collectors.toList());

        //更新到数据库中
        articleService.updateBatchById(articles);

    }
}
